import json
from django.http import HttpResponse
from django.views import View
from apps.menu.models import MainMenu, SubMenu
from utils import ResponseMessage


class MainMenuView(View):
    def get(self, request):
        main_menu = MainMenu.objects.all()
        result_json = {'status': 1000, 'data': []}
        for item in main_menu:
            # print(item)  # item是对象 MainMenu object (1)  MainMenu object (2)  MainMenu object (3) MainMenu object (4)........
            # print(item.to_dict())  # 字典类型 {'main_menu_id': 1, 'main_menu_name': '家用电器'}{'main_menu_id': 2, 'main_menu_name': '手机'}{'main_menu_id': 2, 'main_menu_name': '运营商'}
            result_json['data'].append(item.to_dict())   #要通过每个item对象里的to_dict方法序列化对象
            # print(result_json)  # 字典，并不是JSON格式的数据
            # print(type(json.dumps(result_json)))
        return HttpResponse(json.dumps(result_json), content_type='application/json')
        # json.drup()将字典转化为JSON，content_type='application/json'告诉客户端这个响应是JSON格式的数据，客户端应该相应地处理它。

class SubMenuView(View):
    def get(self, request):
        # 获取请求的参数
        param_id = request.GET['main_menu_id']
        sub_menu = SubMenu.objects.filter(main_menu_id=param_id)
        # result_json = {'status':1000, 'data': []}
        # for item in sub_menu:
        #     result_json['data'].append(item.to_dict())
        # return HttpResponse(json.dumps(result_json), content_type="application/json")
        # 封装一个同意接受数据返回请求的方法
        return ResponseMessage.MenuResponse.success(sub_menu)